import {
	requestPort
} from '@/utils/request.js';
//提示信息
export const showTip = (title, duration = 1300, mask = false, icon = 'none') => {
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
}

export function previewImg(current, url) {
	uni.previewImage({
		current: current,
		urls: url,
	});
}

//毫秒数转成年月日时分秒（24小时制 Y-M-D H:m:s）小于10补0
export const formatTime = (time, type) => {
	var date = new Date(time)
	var year = date.getFullYear()
	var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
	var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
	var hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
	var minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
	var second = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
	if (type == 'Y-M-D H:m:s') {
		var result = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
	} else if (type == 'Y-M-D') {
		var result = year + '-' + month + '-' + day
	} else if (type == 'H:m:s') {
		var result = hour + ':' + minute + ':' + second
	} else if (type == 'Y-M-D H:m') {
		var result = year + '-' + month + '-' + day + ' ' + hour + ':' + minute
	} else if (type == 'H:m') {
		var result = hour + ':' + minute
	} else if (type == 'Y-M') {
		var result = year + '-' + month
	} else if (type == 'Y') {
		var result = year
	} else if (type == 'M') {
		var result = month
	} else if (type == 'D') {
		var result = day
	} else if (type == 'H') {
		var result = hour
	} else if (type == 'm') {
		var result = minute
	} else if (type == 's') {
		var result = second
	}
	return result
}

//毫秒数相减转换成天数
export function calculateDays(startDate, endDate) {
	startDate = new Date(startDate).getTime();
	endDate = new Date(endDate).getTime();
	const difference = endDate - startDate; // 毫秒数差值
	const millisecondsInADay = 24 * 60 * 60 * 1000; // 一天的毫秒数
	const days = Math.floor(difference / millisecondsInADay); // 转换为天数
	return days;
}

// 年月日
export function parseTimeDot(time, cFormat) {
	if (arguments.length === 0) {
		return null
	}
	const format = cFormat || '{y}年{m}月{d}日'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if (('' + time).length === 10) time = parseInt(time) * 1000
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key]
		if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
		if (result.length > 0 && value < 10) {
			value = '0' + value
		}
		return value || 0
	})
	return time_str
}

// 去除html中的image标签
export function removeImgTag(str) {
	str = str.replace(/<img[^>]*>/g, '');
	return str;
}


// 文字高亮 keyword 需要高亮的文字
export const hightLightText = (text, keyword) => {
	if (!text) return
	for (let key of keyword) {
		if (hasSpecialStr(key)) {

		} else {
			const reg = new RegExp(key, 'gi') // 动态正则表达式
			text = text.replace(reg, `<em>${key}</em>`) // 使用replace替换
		}
	}
	return text
};


// JS判断字符串是否含有特殊符号，包括英文与中文两种输入模式。
function hasSpecialStr(str) {
	var specialChars = "~·`!！@#$￥%^…&*()（）—-_=+[]{}【】、|\\;:；：'\"“‘,./<>《》?？，。emEM";
	if (specialChars.indexOf(str) != -1) return true
	return false;
};


//判断是否有网络
export function getNetworkOk() {
	return new Promise((resolve, reject) => {
		uni.getNetworkType({
			success: function(res) {
				if (res.networkType === "none") {
					console.log("当前无网络");
					resolve(false);
				} else {
					resolve(true);
				}
			}
		});
	});
}


// app跳小程序
export function appJumpWx(id) {
	let wechat = null
	plus.share.getServices(res => {
		wechat = res.find(i => i.id === 'weixin')
		if (wechat) {
			wechat.launchMiniProgram({
				id: id, //小程序原始id
				path: '/pagesMy/attentionWechat/attentionWechat', //小程序跳转路径
				type: 0, //可取值： 0-正式版； 1-测试版； 2-体验版。 默认值为0
			}, src => {
				console.log("success:", JSON.stringify(src))
			}, err => {
				console.log("error:", JSON.stringify(err))
			})
		} else {
			uni.showToast({
				title: '当前环境不支持微信操作',
				icon: "none"
			});
		}
	}, function() {
		uni.showToast({
			title: "获取服务失败，不支持该操作。" + JSON.stringify(e),
			icon: 'none'
		})
	});
}


// 用户分析
export async function getUserAnalyze(type, m_id, url = '', code, describe = '') {
	const params = {
		type,
		m_id,
		...(url && {
			url
		}),
		...(describe && {
			describe
		}),
		code,
	};

	let res = await requestPort({
		url: '/api/index/add_analysedata',
		method: 'POST',
		params,
	});

	if (res.code === 1) {
		console.log('用户分析成功');
	}
}

//聊天时间格式化
export function dateTime(e) {
	let old = new Date(e);
	let now = new Date();

	// 获取old具体时间并格式化小时和分钟
	let h = ('0' + old.getHours()).slice(-2);
	let m = ('0' + old.getMinutes()).slice(-2);

	let Y = old.getFullYear();
	let M = ('0' + (old.getMonth() + 1)).slice(-2);
	let D = ('0' + old.getDate()).slice(-2);

	let nY = now.getFullYear();
	let nM = ('0' + (now.getMonth() + 1)).slice(-2);
	let nD = ('0' + now.getDate()).slice(-2);

	// 当天的时间
	if (D === nD && M === nM && Y === nY) {
		return h + ':' + m;
	}

	// 昨天时间
	if (D - 1 === nD && M === nM && Y === nY) {
		return '昨天 ' + h + ':' + m;
	}

	// 今年其他日期
	if (Y === nY) {
		return M + '月' + D + '日 ' + h + ':' + m;
	}

	// 大于今年
	return Y + '年' + M + '月' + D + '日 ' + h + ':' + m;
}